package com.qf.filter;

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author hanjiejie
 * @version V1.0
 * @Project java2203
 * @Package com.qf.filter
 * @Description:
 * @Date 2022/5/23 15:24
 */
//todo 只过滤去/user控制器的过滤器
@WebFilter("/user")
public class PermFilter implements Filter {
    //初始化
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      //1获取用户的访问路径
      HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //获取到用户访问路径
        String uriStr = request.getRequestURI();
        System.out.println("====uriStr=="+ uriStr);
        //2.判断用户路径，放行所有资源 ，放行用户登录的路径，放行用户注册
        //首页，商品查询等路径 判断路径的扩展名 如果是js文件放行，因为js文件和jsp文件
        //相差一个字母， 使用contains无法判断

        if (uriStr.lastIndexOf(".")>0){
            String extStr = uriStr.substring(uriStr.lastIndexOf("."));
            if (extStr !=null){
                if (".js".equals(extStr)){
                    //放行
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }

            }
        }
        if (uriStr.contains("/login")||uriStr.contains("/code")
                ||uriStr.contains("/user")|| uriStr.contains("/register")
                ||uriStr.contains("/index")|| uriStr.contains("/cart")
        || uriStr.contains(".css")|| uriStr.contains("/type")
        || uriStr.contains(".jpg") || uriStr.contains(".png")
        ||uriStr.contains(".gif") || uriStr.contains(".eot")
        || uriStr.contains(".svg")|| uriStr.contains(".ttf")
        || uriStr.contains(".woff")|| uriStr.contains(".woff2")){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //3. 获取会话session对象
        HttpSession session = request.getSession();
        //4.判断会话中是否由用户的对象信息
        User user =(User) session.getAttribute("admin");
        if ( user !=null){
            //5.有放行
            filterChain.doFilter(servletRequest,servletResponse);

        }else {
            //5.没有，让用户重定向到登录页面 重新登录
            response.sendRedirect("login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
